import React, {Component} from 'react';
import './index.less';
import {base, high} from 'nc-lightapp-front';
import Header from '../components/Header';
import SearchModal from '../components/SearchModal';
import AgreeSearchModal from '../components/AgreeSearchModal';
import getConTableData from './functions/getConTableData';
import getAgreeTableData from './functions/getAgreeTableData';
import ContractDetail from '../components/ContractDetail';
import ContractTable from '../components/ContractTable';
import AgreementDetail from '../components/AgreementDetail';
import AgreementTable from '../components/AgreementTable';
import toggleModal from './functions/toggleModalVisible';
import updateButtonStatus from './functions/updateButtonStatus';
import EmptyImg from 'src/hrpub/common/components/emptyImg';
import processTemplate from './functions/processTemplateData';
import saveData from './functions/saveData';
import cancelEdit from './functions/cancelEdit';
import editData from './functions/editData';
import editAgree from './functions/editAgree';
import editContract from './functions/editContract';
import viewAgree from './functions/viewAgree';
import viewContract from './functions/viewContract';
import resetAllpks from './functions/resetAllpks';
import tempPrint from './functions/tempPrint';
import Uploader from "../components/Uploader";
import AlertModal from "../components/AlertModal";
import ContractTextViewAction from './functions/contractTextViewAction';
import AgreeTextViewAction from './functions/agreeTextViewAction';
import checkBtnPermission from "./functions/checkBtnPermission";
import {getAppPageConfig} from "src/hrpub/common/utils/utils";
import WpsModal from 'src/hrpub/common/components/wpsPreModel';
import nodeRefs from './pageIns';
const {NCTabs} = base;
const NCTabPane = NCTabs.NCTabPane;

// handleHash('2019822191712119', '/ifr?page=20198162232323&c=60110315&p=60110315p&ar=0001Z700APPN60110315')

class Account extends Component {
    constructor(props) {
        super(props);
        this.registed = ['dataCard', 'dataBefore', 'dataAfter', 'dataBase', 'postcontCard', 'secrerycontCard', 'traincontCard', 'agreementCard', 'postcontCardBefore', 'postcontCardAfter', 'secrerycontCardBefore', 'secrerycontCardAfter', 'traincontCardBefore', 'traincontCardAfter', 
        'traincontAgreeInfo', 'traincontTrainInfo', 'traincontBusinessInfo', 'agreementList', 'contractList']
        if (props.use) {
            props.use.form('dataCard', 'dataBefore', 'dataAfter', 'dataBase', 'postcontCard', 'secrerycontCard', 'traincontCard', 'agreementCard', 'postcontCardBefore', 'postcontCardAfter', 'secrerycontCardBefore', 'secrerycontCardAfter', 'traincontCardBefore', 'traincontCardAfter', 'traincontAgreeInfo', 'traincontTrainInfo', 'traincontBusinessInfo')
            props.use.table('agreementList', 'contractList')
            props.use.search('contractquery', 'agreementquery')
        }
        this.config = getAppPageConfig();
        this.state = {
            tabKey: 'contract',
            orgVal: {},
            json: {},
            contractPage: 'main',
            lastContractPage: 'main',
            contractAllpks: '',
            contractPageInfo: {
                pageSize: 10,
                pageIndex: 1,
                total: 0,
                totalPage: 1
            },
            contractArea: '',
            agreementPage: 'main',
            lastAgreementPage: 'main',
            agreeArea: '',
            agreeAllpks: '',
            agreementPageInfo: {
                pageSize: 10,
                pageIndex: 1,
                total: 0,
                totalPage: 1
            },
            searched: false,
            pk_psndocList: [],
            isQueryTemplate: false,
            showUploader: false,
            contractData: null,
            agreeData: null,
            psndoc: '',
            agreeAppCode: '',
            contAppCode: '',
            searchModalValue: {
                logic: 'and',
                conditions: []
            }
        };

        props.MultiInit.getMultiLang({
            moduleId: 'cm6011', domainName: 'hrcm', callback: (json, status, inlt) => {
                if (status) {
                    this.setState({json, inlt}, () => {
                        props.createUIDom(this.config, async (data) => {
                            this.setState({
                                buttons: data.button || [],
                                context: data.context || {},
                                queryOid: data.template.contractquery.oid,
                                agreeQueryOid: data.template.agreementquery.oid
                            });
                            data.template = await processTemplate.call(this, data.template);
                            let temp = data.template
                            for (let key in temp) {
                                if(temp.hasOwnProperty(key) && temp[key].moduletype){
                                    if(!this.registed.includes(temp[key].code)) {
                                        temp[key].moduletype === 'form' && props.use.form(temp[key].code);
                                        temp[key].moduletype === 'table' && props.use.editTable(temp[key].code);
                                        this.registed.push(temp[key].code);
                                    }
                            　　}
                            }
                            props.meta.setMeta(data && data.template ? data.template : {});
                            props.button.setButtons(data && data.button ? data.button : {});
                            this.updateButtonStatus();
                            //this.getConTableData();
                        });
                    })//存json和inlt到页面state中并刷新页面
                }
            }
        });
        this.updateState = this.updateState.bind(this);
        this.toggleModal = this.toggleModal.bind(this);
        this.tabChange = this.tabChange.bind(this);
        this.updateOrgValue = this.updateOrgValue.bind(this);
        this.getConTableData = this.getConTableData.bind(this);
        this.getAgreeTableData = this.getAgreeTableData.bind(this);
        this.refresh = this.refresh.bind(this);
        this.editContract = this.editContract.bind(this);
        this.editAgreement = this.editAgreement.bind(this);
        this.viewContract = this.viewContract.bind(this);
        this.viewAgree = this.viewAgree.bind(this);
        this.updateButtonStatus = this.updateButtonStatus.bind(this);
        this.cancel = this.cancel.bind(this);
        this.save = this.save.bind(this);
        this.edit = this.edit.bind(this);
        this.viewbooklet = this.viewbooklet.bind(this);
        this.viewAgreeText = this.viewAgreeText.bind(this);
        this.tempPrint = this.tempPrint.bind(this);
        this.checkFileManage = this.checkFileManage.bind(this);
    }

    componentDidMount() {
        // if (window.location.href.match('localhost:3006'))
        //     window.location.hash = '#/ifr?page=2019'
    }

    updateOrgValue(value) {
        this.setState({orgVal: value},
            () => {
                if (this.state.searched) {
                    this.getConTableData();
                    this.getAgreeTableData();
                } else {
                    this.getConTableData();
                }
            }
        );
    }

    updateState(data, callback = () => {
    }) {
        this.setState(data, callback);
    }

    getConTableData(isRefresh) {
        getConTableData.call(this, isRefresh);
    }

    getAgreeTableData(isQueryTemplate, isRefresh) {
        this.setState({
            isQueryTemplate: !!isQueryTemplate
        }, () => {
            getAgreeTableData.call(this, isRefresh);
        })
    }

    updateButtonStatus() {
        updateButtonStatus.call(this);
    }

    // 切换各种弹窗显示隐藏，type为弹窗的显示隐藏state的key值
    toggleModal(type, visible) {
        return toggleModal.call(this, type, visible);
    }

    tabChange(tabKey) {
        resetAllpks.call(this, tabKey);
        this.setState({
            tabKey
        }, () => {
            if (tabKey === 'agreement' && this.state.searched && this.state.agreementPage === 'main') {
                const {agreementPageInfo} = this.state;
                this.setState({
                    agreementPageInfo: {
                        ...agreementPageInfo,
                        pageIndex: 1
                    }
                }, () => {
                    this.getAgreeTableData(true)
                })
            }
            this.updateButtonStatus();
        });
    }

    refresh() {
        if (!this.state.searched) return;
        if (this.state.tabKey === 'contract') {
            this.setState({
                contractPageInfo: {
                    ...this.state.contractPageInfo,
                    pageIndex: 1
                }
            }, () => {
                this.getConTableData(true);
            })
        } else {
            this.setState({
                agreementPageInfo: {
                    ...this.state.agreementPageInfo,
                    pageIndex: 1
                }
            }, () => {
                this.getAgreeTableData(this.state.isQueryTemplate, true);
            })
        }
    }

    edit() {
        editData.call(this);
    }

    editContract(text, record) {
        editContract.call(this, record);
    }

    editAgreement(text, record) {
        editAgree.call(this, record);
    }

    viewContract(text, record) {
        viewContract.call(this, record);
    }

    viewAgree(text, record) {
        viewAgree.call(this, record);
    }

    save() {
        saveData.call(this);
    }

    cancel() {
        cancelEdit.call(this);
    }

    viewbooklet() {
        ContractTextViewAction.call(this);
    }

    viewAgreeText() {
        AgreeTextViewAction.call(this);
    }

    checkFileManage() {
        const {tabKey, contractData, agreeData} = this.state;
        checkBtnPermission(tabKey === 'contract' ? contractData.rows[0].values.pk_psndoc_sub.value : agreeData.rows[0].values.pk_agreement.value,
            'attachment', tabKey, () => {
                this.setState({
                    showUploader: true
                })
            })
    }

    fileManage(psndoc) {
        this.setState({
            psndoc,
            showUploader: true
        })
    }

    tempPrint() {
        tempPrint.call(this);
    }

    render() {
        const {
            orgVal, tabKey, contractPage, agreementPage, showUploader, json, psndoc,
            contractArea, contractData, agreeArea, agreeData, isQueryTemplate,
            contractPageInfo, agreementPageInfo, queryOid, agreeQueryOid,
            agreeAppCode, contAppCode
        } = this.state;
        const {table} = this.props;
        const isEdit = contractPage === 'edit' || agreementPage === 'edit';
        return (
            <div className="entry-staff-query nc-bill-card">
                <Header
                    {...this.props}
                    tabKey={tabKey}
                    isEdit={isEdit}
                    orgVal={orgVal}
                    json={json}
                    updateState={this.updateState}
                    updateOrgValue={this.updateOrgValue}
                    refresh={this.refresh}
                    save={this.save}
                    cancel={this.cancel}
                    edit={this.edit}
                    viewbooklet={this.viewbooklet}
                    viewAgreeText={this.viewAgreeText}
                    tempPrint={this.tempPrint}
                    checkFileManage={this.checkFileManage}
                />
                <div className="entry-staff-query-content">
                    {!orgVal.refpk ?
                        <EmptyImg text={json['cm6011-000035']}/> :
                        <NCTabs
                            navtype="turn"
                            contenttype="moveleft"
                            tabBarPosition="top"
                            activeKey={tabKey}
                            onChange={this.tabChange}
                        >
                            <NCTabPane tab={json['cm6011-000068']} key={'contract'}>{/* 国际化处理： 合同信息*/}
                                <div style={{display: contractPage === 'main' ? '' : 'none'}}>
                                    <ContractTable
                                        table={table}
                                        updateState={this.updateState}
                                        pageInfo={contractPageInfo}
                                        getConTableData={this.getConTableData}
                                        view={this.viewContract}
                                    />
                                </div>
                                {contractPage === 'main' ? null :
                                    <ContractDetail
                                        {...this.props}
                                        orgVal={orgVal}
                                        page={contractPage}
                                        areaCode={contractArea}
                                        data={contractData}
                                        appCode={contAppCode}
                                        view={this.viewContract}
                                        updateState={this.updateState}
                                        updateButton={this.updateButtonStatus}/>}
                            </NCTabPane>
                            <NCTabPane tab={json['cm6011-000069']} key={'agreement'}>{/* 国际化处理： 协议信息*/}
                                <div style={{display: agreementPage === 'main' ? '' : 'none'}}>
                                    <AgreementTable
                                        table={table}
                                        isQueryTemplate={isQueryTemplate}
                                        updateState={this.updateState}
                                        view={this.viewAgree}
                                        pageInfo={agreementPageInfo}
                                        getAgreeTableData={this.getAgreeTableData}/>
                                </div>
                                {agreementPage === 'main' ? null :
                                    <AgreementDetail
                                        {...this.props}
                                        orgVal={orgVal}
                                        page={agreementPage}
                                        pageInfo={agreementPageInfo}
                                        areaCode={agreeArea}
                                        data={agreeData}
                                        appCode={agreeAppCode}
                                        isQueryTemplate={isQueryTemplate}
                                        view={this.viewAgree}
                                        updateState={this.updateState}
                                        updateButton={this.updateButtonStatus}
                                        getAgreeTableData={this.getAgreeTableData}
                                    />}
                            </NCTabPane>
                        </NCTabs>}
                </div>

                <SearchModal {...this.props}
                             json={json}
                             queryOid={queryOid}
                             pageInfo={contractPageInfo}
                             updateState={this.updateState}
                             getConTableData={this.getConTableData}/>

                <AgreeSearchModal {...this.props}
                                  json={json}
                                  queryOid={agreeQueryOid}
                                  pageInfo={agreementPageInfo}
                                  updateState={this.updateState}
                                  getAgreeTableData={this.getAgreeTableData}/>

                <AlertModal ref={node => this.alertModalNode = node} json={json}/>

                {showUploader && <Uploader
                    tabKey={tabKey}
                    json={json}
                    psndoc={psndoc}
                    contractPage={contractPage}
                    contractData={contractData}
                    agreeData={agreeData}
                    agreementPage={agreementPage}
                    onClose={this.toggleModal('showUploader', false)}/>}
                     <WpsModal
                        {...this.props}
                        onRef ={ref => nodeRefs.wpsview = ref}
                        appcode={getAppPageConfig().appcode}
                        pk_org={orgVal}
                   />
            </div>
        );
    }
}

export default Account;
